package cn.com.hhrcw.web;

import cn.com.hhrcw.entity.EnInfo;
import cn.com.hhrcw.entity.OpCollection;
import cn.com.hhrcw.entity.OpJob;
import cn.com.hhrcw.entity.SysUser;
import cn.com.hhrcw.mapstruct.OpCollectionConvert;
import cn.com.hhrcw.params.CommonParams;
import cn.com.hhrcw.params.OpCollectionParams;
import cn.com.hhrcw.service.IEnInfoService;
import cn.com.hhrcw.service.IOpCollectionService;
import cn.com.hhrcw.service.IOpJobService;
import cn.com.hhrcw.utils.SubjectUtils;
import cn.com.hhrcw.vo.CollectStateAllVO;
import cn.com.hhrcw.vo.CollectStateVO;
import cn.com.hhrcw.vo.OpCollectionVO;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.base.entity.AttributesValueParams;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

/**
 * 职位=收藏职位
 *
 * @author jiangdong
 * @since 2020-10-29
 */
@RestController
@Slf4j
@RequestMapping("/personal/v1/opCollection")
@Api(tags = "职位=收藏职位")
@Validated
public class OpCollectionController extends JeecgController<OpCollection, IOpCollectionService> {

    @Autowired
    private IOpCollectionService opCollectionService;

    @Autowired
    private OpCollectionConvert opCollectionConvert;
    @Autowired
    private IOpJobService jobService;
    @Autowired
    private IEnInfoService enInfoService;


    /**
     * 收藏职位查询
     *
     * @param params 请求参数
     * @return
     */
    @GetMapping(value = "/list")
    @AutoLog("职位=收藏职位-分页列表查询")
    @ApiOperation(value = "分页列表查询", notes = "分页列表查询")
    public Result<Page<OpCollectionVO>> list(OpCollectionParams params, HttpServletRequest request) {
        QueryWrapper<OpCollection> queryWrapper = QueryGenerator.initQueryWrapper(opCollectionConvert.toEntity(params), request.getParameterMap());
        queryWrapper.eq("del_flag", false);
        SysUser sysUser = (SysUser) SubjectUtils.getSubject();
        queryWrapper.eq("user_id", sysUser.getId());
        if (StringUtils.isBlank(params.getField())) {
            queryWrapper.orderByDesc("create_time");
        } else {
            queryWrapper.orderBy(true, params.getSort(), toUnderlineName(params.getField()));
        }

        IPage<OpCollection> page = opCollectionService.page(params.page(), queryWrapper);
        //分页结果转换器
        Function<OpCollection, OpCollectionVO> fun = opCollection -> {
            OpCollectionVO e = new OpCollectionVO();
            e = opCollectionConvert.toVO(opCollection);
            String jobId = e.getJobId();
            OpJob job = jobService.getById(jobId);
            String companyId = job.getCompanyId();
            EnInfo enInfo = enInfoService.getById(companyId);
            e.setOpJob(job);
            e.setEnInfo(enInfo);
            return e;
        };
        return Result.ok((Page) page.convert(fun));
    }

    /**
     * 根据id查询
     *
     * @param id 数据id
     * @return
     */
    @GetMapping(value = "/queryById")
    @ApiOperation(value = "根据id查询", notes = "根据id查询")
    @PermissionData
    public Result<OpCollectionVO> queryById(String id) {
        OpCollection opCollection = opCollectionService
                .lambdaQuery()
                .eq(OpCollection::getId, id)
                .eq(OpCollection::getDelFlag, false)
                .one();
        if (opCollection == null) {
            throw new JeecgBootException("数据不存在");
        }
        return Result.ok(opCollectionConvert.toVO(opCollection));
    }

    /**
     * 收藏职位
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/add")
    @AutoLog("职位=收藏职位-添加")
    @ApiOperation(value = "添加", notes = "添加")
    public Result<?> add(@RequestBody @Valid OpCollectionParams params) {
        boolean saved = true;
        SysUser sysUser = (SysUser) SubjectUtils.getSubject();
        String key = "USERCOLLECT" + params.getJobId() + sysUser.getId();
        try {

            OpJob opJob = jobService.getById(params.getJobId());

            if (null == opJob || opJob.getDelFlag().equals(true)) {
                return Result.error("收藏失败");
            }
            LambdaUpdateWrapper<OpCollection> queryWrapper =  Wrappers.lambdaUpdate();
            queryWrapper.eq(OpCollection::getDelFlag, false);

            queryWrapper.eq(OpCollection::getUserId, sysUser.getId());
            queryWrapper.eq(OpCollection::getJobId, params.getJobId());
            List<OpCollection> list = opCollectionService.list(queryWrapper);
            if (CollectionUtils.isNotEmpty(list)){
                return Result.error("该职位已收藏");
            }
            OpCollection opCollection = opCollectionConvert.toEntity(params);
            opCollection.setCreateBy(sysUser.getId());
            opCollection.setCreateTime(DateUtil.date());
            opCollection.setDelFlag(false);
            opCollection.setUserId(sysUser.getId());
            opCollection.setTime(DateUtil.date());
            //opCollection.setNo(super.sort("op_collection", Constant.NO_SEED));//FIXME: 编号,可根据情况隐藏
            saved = opCollectionService.save(opCollection);
        } catch (Exception e) {
            throw new RuntimeException(e);

        } finally {
            redisTemplate.delete(key);
        }

        return saved ? Result.ok() : Result.error("添加失败");

    }

    /**
     * 收藏职位状态
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/collectState")
    @AutoLog("职位=收藏职位-状态")
    @ApiOperation(value = "状态", notes = "状态")
    public Result<?> collectState(@RequestBody @Valid OpCollectionParams params) {
        boolean saved = true;
        SysUser sysUser = (SysUser) SubjectUtils.getSubject();
        CollectStateVO vo = new CollectStateVO();
        try {
            OpCollection collection = opCollectionService.lambdaQuery().eq(OpCollection::getJobId, params.getJobId())
                    .eq(OpCollection::getUserId, sysUser.getId())
                    .eq(OpCollection::getDelFlag, false)
                    .one();
            if (null == collection) {
                vo.setCollectState(1);
            } else {
                vo.setCollectState(0);
            }

        } catch (Exception e) {

            throw new RuntimeException(e);
        }

        return Result.ok(vo);

    }
    /**
     * 收藏职位状态(多个id)
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/collectStateList")
    @AutoLog("职位=收藏职位-状态")
    @ApiOperation(value = "状态", notes = "状态")
    public Result<?> collectStateList(@RequestBody @Valid OpCollectionParams params) {
        boolean saved = true;
        SysUser sysUser = (SysUser) SubjectUtils.getSubject();
        //CollectStateVO vo = new CollectStateVO();
        List<CollectStateAllVO> list=new ArrayList<>();
        try {

            String[] split = params.getJobId().split(",");
            for (String s : split) {
                CollectStateAllVO vo=new CollectStateAllVO();
                OpCollection collection = opCollectionService.lambdaQuery().eq(OpCollection::getJobId, s)
                        .eq(OpCollection::getUserId, sysUser.getId())
                        .eq(OpCollection::getDelFlag, false)
                        .one();
                vo.setJobId(s);
                if (null == collection) {
                    vo.setCollectState(1);
                } else {
                    vo.setCollectState(0);
                }
                list.add(vo);
            }





        } catch (Exception e) {

            throw new RuntimeException(e);
        }

        return Result.ok(list);

    }


    /**
     * 编辑
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/edit")
    @AutoLog("职位=收藏职位-编辑")
    @ApiOperation(value = "编辑", notes = "编辑")
    @RequiresPermissions("opCollection:edit")
    public Result<?> edit(@RequestBody @Valid OpCollectionParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        OpCollection opCollection = opCollectionConvert.toEntity(params);
        opCollection.setUpdateBy(sysUser.getId());
        opCollection.setUpdateTime(DateUtil.date());

        boolean updated = opCollectionService.updateById(opCollection);
        return updated ? Result.ok() : Result.error("编辑失败");
    }


    /**
     * 批量删除
     *
     * @param
     * @return
     */
    @PostMapping(value = "/delete")
    @AutoLog("职位=收藏职位-批量删除")
    @ApiOperation(value = "批量删除", notes = "批量删除")
    public Result delete(@RequestBody CommonParams params) {
        SysUser sysUser = (SysUser) SubjectUtils.getSubject();
        LambdaUpdateWrapper<OpCollection> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(OpCollection::getJobId, params.getId())
                .set(OpCollection::getDelFlag, true)
                .set(OpCollection::getUpdateBy, sysUser.getId())
                .set(OpCollection::getUpdateTime, DateUtil.date());

        boolean deleted = opCollectionService.update(updateWrapper);
        return deleted ? Result.ok() : Result.error("删除失败");
    }

    /**
     * 属性值是否重复
     *
     * @return
     */
    @Override
    @GetMapping("/propertyRepeat")
    @ApiOperation(value = "属性值是否重复", notes = "属性值是否重复")
    public Result propertyIsRepeat(@Valid AttributesValueParams params) {
        return super.propertyIsRepeat(params);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param params
     */
    @SneakyThrows
    @GetMapping(value = "/exportXls")
    @ApiOperation(value = "导出excel", notes = "导出excel")
    public Result exportXls(HttpServletRequest request, OpCollectionParams params) {
        OpCollection opCollection = opCollectionConvert.toEntity(params);
        opCollection.setDelFlag(false);
        QueryWrapper<OpCollection> queryWrapper = QueryGenerator.initQueryWrapper(opCollection, request.getParameterMap());
        List<OpCollection> data = opCollectionService.list(queryWrapper);
        ExportParams exportParams = new ExportParams("职位=收藏职位", "职位=收藏职位");
        String url = super.exportXls(exportParams, OpCollectionVO.class, opCollectionConvert.toVO(data));
        return Result.ok((Object) url);
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/importExcel")
    @ApiOperation(value = "通过excel导入数据", notes = "通过excel导入数据")
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, OpCollection.class);
    }

}
